package com.d2.plugins.activiti.util;

import com.d2.modules.system.permission.entity.Role;
import com.d2.modules.system.permission.entity.vo.LoginUser;
import com.d2.modules.system.permission.service.impl.RoleServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.context.SecurityContextImpl;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.List;

@Component
@Slf4j
public class SecurityUtil {


    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private RoleServiceImpl roleMapper;

    public void logInAs(String username) {
        LoginUser user = (LoginUser) userDetailsService.loadUserByUsername(username);
        if (user == null) {
            throw new IllegalStateException("User " + username + " doesn't exist, please provide a valid user");
        }
        log.info("> Logged in as: " + username);
        SecurityContextHolder.setContext(new SecurityContextImpl(new Authentication() {
            @Override
            public Collection<? extends GrantedAuthority> getAuthorities() {
                List<Role> roles = roleMapper.queryRoleByUserId(user.getId());
                Collection<GrantedAuthority> authorities = (Collection<GrantedAuthority>) user.getAuthorities();
                for (Role r : roles) {
//            authorities.add(new SimpleGrantedAuthority(r.getCode()));
                    authorities.add(new SimpleGrantedAuthority("GROUP_" + r.getCode()));
                    authorities.add(new SimpleGrantedAuthority("ROLE_ACTIVITI_USER"));
                }

                return authorities;
            }

            @Override
            public Object getCredentials() {
                return user.getPassword();
            }

            @Override
            public Object getDetails() {
                return user;
            }

            @Override
            public Object getPrincipal() {
                return user;
            }

            @Override
            public boolean isAuthenticated() {
                return true;
            }

            @Override
            public void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException {

            }

            @Override
            public String getName() {
                return user.getUsername();
            }
        }));
        org.activiti.engine.impl.identity.Authentication.setAuthenticatedUserId(username);
    }
}
